package com.logos.controller;

import com.logos.common.Result;
import com.logos.common.ResultCode;
import com.logos.entity.Book;
import com.logos.properties.Enterprise;
import com.logos.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {

    @Value("${lesson}")
    private String lesson;

    @Value("${server.port}")
    private Integer port;

    @Value("${enterprise.likes[0]}")
    private String subject_0;

    @Autowired
    private Environment environment;

    @Autowired
    private Enterprise enterprise;

    @GetMapping("/{id}")
    public String getById(@PathVariable Integer id) {
        System.out.println("id = " + id);
        System.out.println("lesson = " + lesson);
        System.out.println("port = " + port);
        System.out.println("subject_0 = " + subject_0);
        System.out.println("--------------------------------");
        System.out.println(environment.getProperty("lesson"));
        System.out.println(environment.getProperty("server.port"));
        System.out.println(environment.getProperty("enterprise.likes[0]"));
        System.out.println("--------------------------------");
        System.out.println("enterprise = " + enterprise);
        return "hello springboot";
    }

    @Autowired
    private BookService bookService;

    @PostMapping
    public Result insert(@RequestBody Book book) {
        boolean flag = bookService.insert(book);
        return new Result(flag ? ResultCode.SAVE_OK : ResultCode.SAVE_ERR, flag);
    }

    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean flag = bookService.update(book);
        return new Result(flag ? ResultCode.UPDATE_OK : ResultCode.UPDATE_ERR, flag);
    }

    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        boolean flag = bookService.deleteById(id);
        return new Result(flag ? ResultCode.DELETE_OK : ResultCode.DELETE_ERR, flag);
    }

    @GetMapping("/{id}")
    public Result selectById(@PathVariable Integer id) {
        Book book = bookService.selectById(id);
        Integer code = book != null ? ResultCode.GET_OK : ResultCode.GET_ERR;
        String msg = book != null ? "success" : "fail";
        return new Result(code, book, msg);
    }

    @GetMapping
    public Result selectAll() {
        List<Book> bookList = bookService.selectAll();
        Integer code = bookList != null ? ResultCode.GET_OK : ResultCode.GET_ERR;
        String msg = bookList != null ? "success" : "fail";
        return new Result(code, bookList, msg);
    }
}
